﻿using learun.util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using ProjectManApi.mmm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectManApi.Extensions
{
    public class AuthorizeMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IOperator _operator;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="next">请求委托</param>
        /// <param name="ioperator">验证登录信息方法</param>
        public AuthorizeMiddleware(RequestDelegate next, IOperator ioperator)
        {
            _next = next;
            _operator = ioperator;
        }

        /// <summary>
        /// 执行
        /// </summary>
        /// <param name="httpContext">请求连接</param>
        /// <returns></returns>
        public async Task Invoke(HttpContext httpContext)
        {
            //string url = SetUrl(httpContext);
            var endpoint = httpContext.GetEndpoint();
            if (endpoint != null && endpoint.Metadata.GetMetadata<IAllowAnonymous>() == null)
            {
                // 获取请求值
                if (!httpContext.Request.Headers["token"].IsEmpty())
                {
                    string token = httpContext.Request.Headers["token"].ToString();
                    var res = _operator.DecodeToken(token);
                    if (res == "TokenExpiredException")
                    {
                        await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.nologin, info = "登录信息过期" });
                        return;
                    }
                    else if (res == "SignatureVerificationException")
                    {
                        await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.nologin, info = "非法密钥" });
                        return;
                    }
                    else
                    {
                        var payload = res.ToObject<Payload>();
                        ContextHelper.SetItem("account", payload.Account);
                        ContextHelper.SetItem("userId", payload.UserId);
                        ContextHelper.SetItem("userName", payload.UserName);
                    }
                }
                else
                {
                    await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.nologin, info = "权限验证失败" });
                    return;
                }
            }
            else
            {
                if (httpContext.Request.Query.ContainsKey("apiccount"))
                {
                    string account = httpContext.Request.Query["apiccount"];
                    ContextHelper.SetItem("account", account);
                }
            }

            await _next(httpContext);
            return;
        }
        /// <summary>
        /// 返回请求信息
        /// </summary>
        /// <param name="response">返回头</param>
        /// <param name="data">数据</param>
        /// <returns></returns>
        private async Task RespondWithJson(HttpResponse response, object data)
        {
            response.StatusCode = 200;
            response.ContentType = "application/json;charset=utf-8";
            await response.WriteAsync(data.ToJson(), new UTF8Encoding(false));
        }
    }
}
